package com.hankol.community.view;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.baselibrary.utils.NumberUtils;
import com.baselibrary.utils.ScreenUtils;
import com.baselibrary.utils.ToastUtils;
import com.hankol.community.bean.HKVideoBean;
import com.hankol.community.databinding.ActivityPulpitVideoBinding;
import com.tencent.rtmp.ITXVodPlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXVodPlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;

/**
 * @author: 关忆北、
 * @date: 2022/4/28
 * @Des：继承腾讯云的视频播放器 扩展
 */
public class HKVideoView extends TXCloudVideoView implements SeekBar.OnSeekBarChangeListener {
    private Activity activity;
    private ActivityPulpitVideoBinding binding;
    ;
    private TXVodPlayer mTXVodPlayer;
    public boolean isReStar;//播放完成，是否重新播放
    private ProgressBar pBar;//加载视频 loading
    private ImageView ivPlayState;//视频暂停/播放按钮
    private SeekBar sBar;//视频底部进度条
    private ImageView ivCover;//视频封面
    private TextView tvCurrentSpeed;//视频实时进度
    private TextView tvTotalSpeed;//视频总进度
    private ImageView ivFullScreen;//视频全屏
    private RelativeLayout rlVideoFatherView;//承载视频的VIew
    private OnVideoPlayListener mOnVideoPlayListener;
    private String videoUrl;
    private int second;
    private long offset;
    private long lastProgress = 0;
    int UP_PLAYER = 0x1;
    private long mSlidePro = 0;//手指拖动进度条
    private final Handler tHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            if (ivPlayState != null) ivPlayState.setVisibility(View.GONE);
            return false;
        }
    });


    public HKVideoView(Context context) {
        super(context);
        initVideo();
    }

    public HKVideoView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        initVideo();
    }

    public void initVideo() {
        mTXVodPlayer = new TXVodPlayer(getContext());
        setLogMargin(12f, 12f, 110f, 60f);
        showLog(false);
        mTXVodPlayer.setVodListener(new ITXVodPlayListener() {
            @Override
            public void onPlayEvent(TXVodPlayer txVodPlayer, int event, Bundle bundle) {
                switch (event) {
                    case TXLiveConstants.PLAY_EVT_VOD_PLAY_PREPARED:

                        if (ivCover != null) ivCover.setVisibility(GONE);
                        if (pBar != null) pBar.setVisibility(View.GONE);
                        if (ivPlayState != null) ivPlayState.setSelected(true);
                        if (mOnVideoPlayListener != null) mOnVideoPlayListener.onReadyToPlay();

                        break;
                    case TXLiveConstants.PLAY_EVT_PLAY_END:
                        if (isReStar) {
                            mTXVodPlayer.seek(0);
                            mTXVodPlayer.resume();
                        }
                        if (ivPlayState != null) {
                            ivPlayState.setVisibility(VISIBLE);
                            ivPlayState.setSelected(false);
                        }
                        lastProgress = 0;
                        /*因为播放控件缓存的问题，退出再次进入 会回执此方法，且bundle.getInt(TXLiveConstants.EVT_PLAY_DURATION_MS)获取到的是0，所以这里加个判断*/
                        if (mOnVideoPlayListener != null) mOnVideoPlayListener.onPlayComplete();

                        break;
                    case TXLiveConstants.PLAY_EVT_PLAY_PROGRESS:
                        int progress = bundle.getInt(TXLiveConstants.EVT_PLAY_PROGRESS_MS);
                        int duration = bundle.getInt(TXLiveConstants.EVT_PLAY_DURATION_MS);
                        if (sBar.getProgress() == progress)
                            break;//重复回执，不做任何操作
                        if (sBar != null && sBar.getMax() <= 0) {
                            sBar.setMax(duration);
                        }
                        if (sBar != null) sBar.setProgress(progress);
                        if (offset != 0) {
                            mTXVodPlayer.seek(offset / 1000f);
                            offset = 0;
                        }

                        if (tvTotalSpeed != null)
                            tvTotalSpeed.setText(NumberUtils.stringForTime(duration));

                        if (tvCurrentSpeed != null)
                            tvCurrentSpeed.setText(NumberUtils.stringForTime(progress));

                        if (mOnVideoPlayListener != null)
                            mOnVideoPlayListener.onPlayProgress(progress, duration);

                        if (lastProgress == 0 && progress == 0) break;
                        //progress<lastProgress  有可能是手动对视频进行了后退。
                        if (progress / 1000 - lastProgress / 1000 >= second || progress < lastProgress) {
                            //多少秒上报一次
                            if (mOnVideoPlayListener != null)
                                mOnVideoPlayListener.onStudyListener(progress, duration);
                            lastProgress = progress;
                        }
                        break;
                    case TXLiveConstants.PLAY_EVT_PLAY_LOADING:
                        //视频流加载loading
                        if (pBar != null) pBar.setVisibility(View.VISIBLE);
                        break;
                    case TXLiveConstants.PLAY_EVT_VOD_LOADING_END:
                        //视频流加载loading结束
                        if (pBar != null) pBar.setVisibility(View.GONE);
                        break;
                    case TXLiveConstants.PLAY_WARNING_VIDEO_DECODE_FAIL:
                    case TXLiveConstants.PLAY_ERR_NET_DISCONNECT:
                        binding.llLocusVideoError.setVisibility(VISIBLE);
                        pBar.setVisibility(GONE);
                        break;
                }
            }

            @Override
            public void onNetStatus(TXVodPlayer txVodPlayer, Bundle bundle) {

            }
        });
        mTXVodPlayer.setPlayerView(this);
        mTXVodPlayer.setAutoPlay(true);
        mTXVodPlayer.enableHardwareDecode(false); // 是否使用硬解码
        mTXVodPlayer.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT); // player 渲染角度
        mTXVodPlayer.setRenderMode(TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION);
    }

    public void startVideo(Activity activity, HKVideoBean hkVideoBean, String videoUrl, OnVideoPlayListener mOnVideoPlayListener) {
        this.activity = activity;
        this.binding = hkVideoBean.getBinding();
        this.isReStar = hkVideoBean.isReStar();
        this.pBar = hkVideoBean.getPBar();
        this.ivPlayState = hkVideoBean.getIvPlayState();
        this.sBar = hkVideoBean.getSBar();
        this.ivCover = hkVideoBean.getIvCover();
        this.tvCurrentSpeed = hkVideoBean.getTvCurrentSpeed();
        this.tvTotalSpeed = hkVideoBean.getTvTotalSpeed();
        this.ivFullScreen = hkVideoBean.getIvFullScreen();
        this.rlVideoFatherView = hkVideoBean.getRlVideoFatherView();
        this.second = hkVideoBean.getSecond();
        this.offset = hkVideoBean.getOffset();
        this.videoUrl = videoUrl;
        this.mOnVideoPlayListener = mOnVideoPlayListener;
        if (pBar != null) pBar.setVisibility(View.VISIBLE);
        if (ivPlayState != null) ivPlayState.setSelected(true);
        start(videoUrl);
        sBar.setOnSeekBarChangeListener(this);

    }

    private void start(String videoUrl) {
        if (TextUtils.isEmpty(videoUrl)) {
            ToastUtils.showShort(activity.getApplicationContext(), "视频链接出错");
            return;
        }
        mTXVodPlayer.startVodPlay(videoUrl);
        hidePlayerView();
        initListener();

    }

    private void initListener() {
        setOnClickListener(view -> {
            if (ivPlayState != null) {
                if (ivPlayState.getVisibility() == VISIBLE) {
                    ivPlayState.setVisibility(GONE);
                } else {
                    ivPlayState.setVisibility(VISIBLE);
                }
                hidePlayerView();
            }
        });
        if (ivPlayState != null) {
            ivPlayState.setSelected(true);
            ivPlayState.setOnClickListener(view -> {
                hidePlayerView();
                if (mTXVodPlayer.isPlaying()) {
                    mTXVodPlayer.pause();
                    ivPlayState.setSelected(false);
                } else {
                    mTXVodPlayer.resume();
                    ivPlayState.setSelected(true);
                }
            });
        }
        if (ivFullScreen != null) {
            ivFullScreen.setOnClickListener(view -> {
                if (rlVideoFatherView != null) {
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) rlVideoFatherView.getLayoutParams();
                    if (rlVideoFatherView.isSelected()) {
                        if (mOnVideoPlayListener != null) mOnVideoPlayListener.onVerticalScreen();
                        layoutParams.height = ScreenUtils.dip2px(activity, 196);
                    } else {
                        if (mOnVideoPlayListener != null) mOnVideoPlayListener.onHorizontalScreen();
                        layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
                    }

                    rlVideoFatherView.setLayoutParams(layoutParams);
                    activity.setRequestedOrientation(rlVideoFatherView.isSelected() ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    rlVideoFatherView.setSelected(!rlVideoFatherView.isSelected());
                }

            });
        }
        if (binding != null) {
            binding.tvLocusErrorAgain.setOnClickListener(view -> {
                ivPlayState.setVisibility(GONE);
                ivPlayState.setSelected(true);
                pBar.setVisibility(VISIBLE);
                binding.llLocusVideoError.setVisibility(GONE);
                start(videoUrl);
            });
        }
    }

    public void pause() {
        tHandler.removeMessages(UP_PLAYER);
        if (mTXVodPlayer != null && mTXVodPlayer.isPlaying()) {
            sBar.setMax(0);
            sBar.setProgress(0);
            ivPlayState.setSelected(false);
            ivPlayState.setVisibility(VISIBLE);
            mTXVodPlayer.pause();
        }
    }

    public void clear(){
        if (mTXVodPlayer != null){
            mTXVodPlayer.stopPlay(true);
        }
    }

    public void stopPlay() {
        if (mTXVodPlayer != null && mTXVodPlayer.isPlaying()) {
            mTXVodPlayer.stopPlay(true);
        }
    }

    private void hidePlayerView() {
        tHandler.removeMessages(UP_PLAYER);
        tHandler.sendEmptyMessageDelayed(UP_PLAYER, 3000);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        mSlidePro = seekBar.getProgress();
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (mTXVodPlayer != null) {
            //手指抬起获取当前SeekBar进度
            mTXVodPlayer.seek(mSlidePro / 1000);
            mTXVodPlayer.resume();
        }
    }

    /**
     * 一下都是毫秒级
     */
    public interface OnVideoPlayListener {
        //播放进度
        void onPlayProgress(long speed, long totalSpeed);

        //播放完成
        void onPlayComplete();

        //准备播放
        void onReadyToPlay();

        //视频进度上报
        void onStudyListener(long speed, long totalSpeed);

        //横屏
        void onHorizontalScreen();

        //竖屏
        void onVerticalScreen();
    }

}
